import React, { useState, useEffect } from "react";
import {
  Table,
  Input,
  Button,
  message,
  Modal,
  Checkbox,
} from "antd";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import axios from "axios";
import CommonFormModal from "../../components/CommonFormModal";
import { useFormModal } from "../../hooks/useFormModal";
import { productFormConfig } from "../../utils/formConfigs";

// API基础URL
const API_BASE_URL = "http://localhost:3000";

// 定义产品数据类型
interface Product {
  key: string;
  id: string;
  code: string;
  name: string;
  warning: number;
  cate: string;
  title: string;
  price: number;
  add: string;
  edit: string;
  addtime: string;
  edittime: string;
  children?: Product[];
}


// 移除分类选项，不再使用下拉选择

export default function Product() {
  const [productData, setProductData] = useState<Product[]>([]);
  const [filteredData, setFilteredData] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    name: "",
    code: "",
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [inventoryData, setInventoryData] = useState<Inventory[]>([]);
  
  // 使用通用表单弹窗Hook
  const {
    visible,
    isAddMode,
    currentRecord,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    loading: _modalLoading,
    openAddModal,
    openEditModal,
    closeModal,
  } = useFormModal<Product>();

  // 获取产品数据
  const fetchProducts = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/foundation/products`);
      // 过滤掉重复的数据（基于编码和名称去重）
      const uniqueProducts = response.data.filter((product: Product, index: number, self: Product[]) => 
        index === self.findIndex((p: Product) => p.code === product.code && p.name === product.name)
      );
      setProductData(uniqueProducts);
      setFilteredData(uniqueProducts);
    } catch (error) {
      console.error('获取产品数据失败:', error);
      message.error('获取产品数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchProducts();
  }, []);

  // 处理搜索
  const handleSearch = () => {
    const filtered = productData.filter((item) => {
      return (
        (searchParams.name === "" ||
          item.name.toLowerCase().includes(searchParams.name.toLowerCase())) &&
        (searchParams.code === "" ||
          item.code.toLowerCase().includes(searchParams.code.toLowerCase()))
      );
    });
    setFilteredData(filtered);
    setCurrentPage(1);
    message.success(`找到 ${filtered.length} 条匹配记录`);
  };

  // 处理重置
  const handleReset = () => {
    setSearchParams({
      name: "",
      code: "",
    });
    setFilteredData(productData);
    setCurrentPage(1);
    message.info("已重置搜索条件");
  };

  // 打开新增产品弹窗
  const handleAddProduct = () => {
    openAddModal();
  };

  // 打开编辑弹窗
  const handleEdit = (record: Product) => {
    openEditModal(record);
  };

  // 确认删除
  const handleDelete = (record: Product) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除产品"${record.name}"吗？`,
      async onOk() {
        try {
          await axios.delete(`${API_BASE_URL}/api/foundation/products/${record.id}`);
          // 重新获取数据
          await fetchProducts();
          message.success("删除成功");
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      },
    });
  };

  // 处理表单提交
  const handleSubmit = async (values: Partial<Product>, isAddMode: boolean, currentRecord?: Product | null) => {
    try {
      if (isAddMode) {
        // 新增
        await axios.post(`${API_BASE_URL}/api/foundation/products`, {
          code: values.code,
          name: values.name,
          warning: values.warning,
          cate: values.cate,
        });
        
        // 重新获取数据
        await fetchProducts();
        message.success("新增成功");
      } else {
        // 编辑
        await axios.put(`${API_BASE_URL}/api/foundation/products/${currentRecord?.id}`, {
          code: values.code,
          name: values.name,
          warning: values.warning,
          cate: values.cate,
        });
        
        // 重新获取数据
        await fetchProducts();
        message.success("编辑成功");
      }
      
      // 操作成功后关闭弹窗
      closeModal();
    } catch (error) {
      console.error('操作失败:', error);
      message.error(isAddMode ? '新增失败' : '编辑失败');
    }
  };

  // 表格列定义 
  const columns = [
    {
      title: (
        <Checkbox
          indeterminate={selectedRows.length > 0 && selectedRows.length < filteredData.length}
          checked={selectedRows.length === filteredData.length && filteredData.length > 0}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedRows(filteredData.map((item) => item.id));
            } else {
              setSelectedRows([]);
            }
          }}
        />
      ),
      key: "selection",
      width: 50,
      render: (_: unknown, record: Product) => (
        <Checkbox
          checked={selectedRows.includes(record.id)}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedRows([...selectedRows, record.id]);
            } else {
              setSelectedRows(selectedRows.filter((id) => id !== record.id));
            }
          }}
        />
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      width: 80,
      render: (id: string) => (
        <span style={{ color: '#1890ff', cursor: 'pointer' }}>{id}</span>
      ),
    },
    {
      title: "编码",
      dataIndex: "code",
      key: "code",
      width: 100,
    },
    {
      title: "物品名称",
      dataIndex: "name",
      key: "name",
      width: 120,
    },
    {
      title: "预警库存",
      dataIndex: "warning",
      key: "warning",
      width: 100,
    },
    {
      title: "分类",
      dataIndex: "cate",
      key: "cate",
      width: 100,
    },
    {
      title: "创建人",
      dataIndex: "add",
      key: "add",
      width: 100,
    },
    {
      title: "创建时间",
      dataIndex: "addtime",
      key: "addtime",
      width: 120,
    },
    {
      title: "修改人",
      dataIndex: "edit",
      key: "edit",
      width: 100,
      render: (edit: string) => (
        <span style={{ color: '#1890ff', cursor: 'pointer' }}>{edit}</span>
      ),
    },
    {
      title: "修改时间",
      dataIndex: "edittime",
      key: "edittime",
      width: 120,
      render: (edittime: string) => (
        <span style={{ color: '#1890ff', cursor: 'pointer' }}>{edittime}</span>
      ),
    },
    {
      title: "操作",
      key: "operation",
      width: 150,
      render: (_: unknown, record: Product) => (
        <div style={{ display: 'flex', gap: '8px', alignItems: 'center', whiteSpace: 'nowrap' }}>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleEdit(record);
            }}
            style={{ color: '#1890ff', whiteSpace: 'nowrap' }}
          >
            编辑
          </a>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleDelete(record);
            }}
            style={{ color: '#1890ff', whiteSpace: 'nowrap' }}
          >
            删除
          </a>
        </div>
      ),
    },
  ];

  // 分页配置 - 按照原型图设计
  const pagination = {
    current: currentPage,
    pageSize: pageSize,
    total: filteredData.length,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) =>
      `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
    showLessItems: true,
    onChange: (page: number, size: number) => {
      setCurrentPage(page);
      setPageSize(size);
    },
    onShowSizeChange: (current: number, size: number) => {
      setCurrentPage(1);
      setPageSize(size);
    },
  };

  return (
    <div style={{ 
      padding: "20px", 
      minHeight: "100vh",
      fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif"
    }}>
      {/* 搜索区域 */}
      <div
        style={{
          padding: "20px",
          marginBottom: "20px",
        }}
      >
        <div style={{ display: "flex", gap: "16px", marginBottom: "16px", alignItems: "center" }}>
          <Input
            placeholder="请输入名称"
            value={searchParams.name}
            onChange={(e) =>
              setSearchParams({ ...searchParams, name: e.target.value })
            }
            style={{ width: "200px" }}
            suffix={<SearchOutlined style={{ color: "#bfbfbf" }} />}
          />
          <Input
            placeholder="请输入物品编号"
            value={searchParams.code}
            onChange={(e) =>
              setSearchParams({ ...searchParams, code: e.target.value })
            }
            style={{ width: "200px" }}
            suffix={<SearchOutlined style={{ color: "#bfbfbf" }} />}
          />
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </div>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleAddProduct}
        >
          新增物品
        </Button>
      </div>

      {/* 表格区域 */}
      <Table
        columns={columns}
        dataSource={filteredData}
        pagination={pagination}
        scroll={{ x: 1200, y: "calc(100vh - 500px)" }}
        size="middle" 
        loading={loading}
        rowKey="id"
        expandable={{
          showExpandColumn: false, // 隐藏展开/折叠列
          expandedRowKeys:[]
        }}
      />

      {/* 新增/编辑弹窗 */}
      <CommonFormModal
        visible={visible}
        title={isAddMode ? "新增物品" : "编辑物品"}
        isAddMode={isAddMode}
        currentRecord={currentRecord}
        formItems={productFormConfig}
        onSubmit={handleSubmit}
        onCancel={closeModal}
        loading={loading}
        width={600}
      />
    </div>
  );
}